import Router, { Middleware } from '@koa/router';
import { glob } from 'glob';

import Koa from 'koa';

export const router = new Router();
type Method = 'get' | 'post' | 'put' | 'all' | 'delete';
export function routerCreator(p: string, ...mi: Middleware[]) {
  function method(me: Method, pa: string, ...mid: Middleware[]) {
    mid = mi.concat(mid);
    pa = `/${p.split('/').concat(pa.split('/')).filter(Boolean).join('/')}`;
    router[me](pa, ...mid);
    console.log(`[${me}]`, pa, mid);
  }
  return {
    get: (pa: string, ...m: Middleware[]) => method('get', pa, ...m),
    post: (pa: string, ...m: Middleware[]) => method('post', pa, ...m),
    all: (pa: string, ...m: Middleware[]) => method('all', pa, ...m),
    put: (pa: string, ...m: Middleware[]) => method('put', pa, ...m),
    delete: (pa: string, ...m: Middleware[]) => method('delete', pa, ...m),
  };
}
export const routes = async (app: Koa) => {
  const files = await glob('../action/**/*.js', { cwd: __dirname });
  files.forEach((file) => require(file));

  app.use(router.routes());
  app.use(router.allowedMethods());
};
